import time

import requests, json
import datetime
import sys
import ntplib
########################### Yyuan
file_name = "Yyuan"
actId = 2408290029735265
actGoodId1 = 563747638
Authorization = "eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjE4ODQ3Mjc4OCwiZXhwIjoxNzI1NTMyNjg0fQ.G8cIEz5sNloX-2dbdmf2wczLimMHS9K6F3tet5OBBybp9QRRPLHnVvqs-UAj8FHpHKOaXrCxt4iy4jtSi7peHQ"
proxies = {"http": None, "https": None}
logname = "bm_Yyuan.log"
yanshi = 1.8
if len(sys.argv) > 1:
    yanshi = float(sys.argv[1].strip())
userInfo = {
    "linkMan": "徐真真",
    "linkPhone": "13298257025",
    "phonePrefix": "86",
    "province": "河南省",
    "city": "许昌市",
    "country": "魏都区",
    "linkAddress": "八一路东站前府",
    "userAddrId": 8415430
}
###########################
servertime_s = 0
servertime_ms = 0
ntpclient = ntplib.NTPClient()
stime = time.time()
resp = ntpclient.request("ntp.aliyun.com")
etime = time.time()
print(etime, resp.tx_time)
dtime = resp.tx_time - etime + (etime - stime) / 2
if abs(dtime) >= 1:
    servertime_s = dtime // 1
servertime_ms = (dtime % 1) * 1000 // 1


data = {
	"activityId": "{}".format(actId),
	"enterStatus": 1
}

info_url = "https://apipro.qunjielong.com/activity-biz/activity/detail/frame/apply"
# info_url = "https://apipro.qunjielong.com/activity-biz/activity/detail/frame/group_buy"

headers = {
    "Host": "apipro.qunjielong.com",
    "Connection": "keep-alive",
    "device-type": "10",
    "mini-route": "pro/pages/homepage/customer-homepage/customer-homepage",
    "Authorization": Authorization,
    "uid": "188472788",
    "companyId": "190",
    "feature-tag": "f0000",
    "qjl-request-level": "LV1",
    "client-version": "5.6.82",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090b19)XWEB/11253",
    "Content-Type": "application/json",
    "xweb_xhr": "1",
    "appid": "wx059cd327295ab444",
    "sceneCode": "1145",
    "version": "3.0.0",
    "Accept": "*/*",
    "Sec-Fetch-Site": "cross-site",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Dest": "empty",
    "Referer": "https://servicewechat.com/wx059cd327295ab444/1885/page-frame.html",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9"
}

stime = time.time()
res = requests.post(info_url, headers=headers, data=json.dumps(data), proxies=proxies)
dtime_qunjielong = (time.time() - stime) / 2
js = res.json()
stime = datetime.datetime.now()
if js.get("data") and js.get("data").get("activity") and js.get("data").get("activity").get("startTime"):
    stime = datetime.datetime.fromtimestamp(js.get("data").get("activity").get("startTime") / 1000)
    stime -= datetime.timedelta(seconds=1)

print("时差{}.{}".format(int(servertime_s), int(servertime_ms)))
print(stime.strftime("%Y-%m-%d %H:%M:%S"))
print("延时：" + str(yanshi))
print("IO时间:{}ms".format(int(dtime_qunjielong * 1000)))

while (datetime.datetime.now() + datetime.timedelta(seconds=servertime_s) + datetime.timedelta(milliseconds=servertime_ms)) < stime:
    pass

time.sleep(yanshi)

place_all = "https://apipro.qunjielong.com/order-place/api/mina/order_place/place-all"

def run(f_w):
    try:
        data = {
            "signUpOrderDTO": {
                "userInfo": userInfo,
                "proOrderItemParamList": [{
                    "actGoodId": actGoodId1,
                    "buyQuantity": 1
                }],
                "dlvAddrId": 0,
                "proOrderDefExts": [],
                "markInfoJson": {},
                "orderDefItemList": []
            },
            "actId": actId
        }
        print(data)
        res = requests.post(place_all, headers=headers, data=json.dumps(data), proxies=proxies)
        print(file_name)
        print(res.text)
        f_w.write(json.dumps(res.json(), indent=4, ensure_ascii=False, sort_keys=True))
        f_w.write("\n")
        if res.json().get("data").get("success"):
            query_order_personal_home_page = "https://apipro.qunjielong.com/order-cert/api/mina/user-order/query_order_personal_home_page?page=1&pageSize=1"
            res = requests.post(query_order_personal_home_page, data=json.dumps({}), headers=headers, proxies=proxies)
            f_w.write(json.dumps(res.json(), indent=4, ensure_ascii=False, sort_keys=True))
            f_w.write("\n")
            return True
    except Exception as e:
        print(e)
        return False

with open(logname, "w", encoding="utf-8") as f_w:
    for i in range(1):
        f_w.write(file_name + "\n")
        f_w.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") + "\n")
        if run(f_w):
            break
        time.sleep(0.2)

